import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class newCoutrolerPanel extends javax.swing.JFrame implements
    ActionListener
{
  static int serviceNo = 0;
  public JButton CreteTimeTable;
  //Date startDate = new Date(112, 5, 24);
  int startTime, endTime, tHours;
  int lastEndTime = 0;
  int lastServiceNo = 0;
  int driverNoA = 0;
  public JScrollPane jScrollPane1;
  public JTextArea TimeTable;
  private JTextField dateStart;
  private JLabel explainText;
  private JPanel DateSelect;
  Date startDate;
  Driver driverRoster[] = new Driver[80];
  int service[] = new int[80];
  static FileWriter fstream;
  static PrintWriter out;
  static FileWriter pstream;
  static PrintWriter pout;
  static FileReader reader = null;

  /**
   * Auto-generated main method to display this JFrame
   */
  /*
   * public static void main(String[] args) { SwingUtilities.invokeLater(new
   * Runnable() { public void run() { controlerPanel inst = new
   * controlerPanel(); inst.setLocationRelativeTo(null); inst.setVisible(true);
   * } });
   * 
   * }
   */
  public newCoutrolerPanel()
  {
    super();
    initGUI();
  }

  private void initGUI()
  {
    try
    {
      setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
      this.setLocationByPlatform(true);
      this.setResizable(false);
      {
        jScrollPane1 = new JScrollPane();
        getContentPane().add(jScrollPane1, BorderLayout.NORTH);
        jScrollPane1.setPreferredSize(new java.awt.Dimension(453, 202));
        {
          TimeTable = new JTextArea();
          jScrollPane1.setViewportView(TimeTable);
          TimeTable.setPreferredSize(new java.awt.Dimension(439, 10000));
          TimeTable.setAutoscrolls(false);
          TimeTable.setFont(new java.awt.Font("Monospaced", 0, 12));
        }
      }
      {
        CreteTimeTable = new JButton();
        BorderLayout CreteTimeTableLayout = new BorderLayout();
        getContentPane().add(CreteTimeTable, BorderLayout.SOUTH);
        CreteTimeTable.setLayout(CreteTimeTableLayout);
        CreteTimeTable.setText("CreteTimeTable");
        CreteTimeTable.setPreferredSize(new java.awt.Dimension(457, 28));
        CreteTimeTable.addActionListener(this);
      }
      {
        DateSelect = new JPanel();
        getContentPane().add(DateSelect, BorderLayout.CENTER);
        DateSelect.setLayout(null);
        {
          explainText = new JLabel();
          DateSelect.add(explainText);
          explainText
              .setText("Please type in the start day of the weekly timetable(dd/mm/YYYY):  ");
          explainText.setBounds(7, 4, 469, 15);
        }
        {
          dateStart = new JTextField();
          DateSelect.add(dateStart);
          dateStart.setBounds(482, 1, 117, 22);
        }
      }
      pack();
      this.setSize(602, 283);
    }
    catch (Exception e)
    {
      // add your error handling code here
      e.printStackTrace();
    }
  }

  public void actionPerformed(ActionEvent event)
  {
    if (event.getSource() == CreteTimeTable)
    {

      /*
       * // Print one week timetable for one route for (int x=0; x<7; x++) {
       * startDate.setDate(startDate.getDate()+1); int[] serviceTimesd =
       * TimetableInfo.getServiceTimes(65, startDate, 0); for (int y=0; y<
       * serviceTimesd.length; y++) { System.out.println(serviceTimesd[y]);
       * System.out.println(startDate); } }
       */
      try
      {
        // Create file
        fstream = new FileWriter("timetable.txt");
        out = new PrintWriter(fstream);

        // Close the output stream

      }
      catch (Exception e)
      {// Catch exception if any
        System.err.println("Error:1 " + e.getMessage());
      }

      String startDateS = dateStart.getText();
      boolean s = isValidDate(startDateS);

      if (s == true)
      {
        try
        {
          DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
          startDate = df.parse(startDateS);

        }
        catch (ParseException e)
        {
          System.err.println("Caught IOException: " + e.getMessage());
        }

        if (startDate.getDay() == 1)
        {

          for (int x = 0; x < 5; x++)
          {
            for (int driverNoA = 0; driverNoA < 70; driverNoA++)
            {
              lastEndTime = 0;
              int totalHours = 0;
              for (serviceNo = 0; serviceNo < 61; serviceNo++)
              {
                if (service[serviceNo] != 1)
                {
                  int[] serviceTimesd = TimetableInfo.getServiceTimes(65,
                      startDate, serviceNo);
                  int[] driverID = DriverInfo.getDrivers();

                  for (int i = 0; i < serviceTimesd.length; i++)
                  {
                    // System.out.print(serviceTimesd[i] + " ");
                    if (i == 0)
                    {
                      startTime = serviceTimesd[i];
                    }
                    if (i == (serviceTimesd.length - 1))
                    {
                      endTime = serviceTimesd[i];
                    }
                  }
                  //System.out.println("test3");
                  if ((startTime - lastEndTime) >= 20)
                  {
                    tHours = endTime - startTime;
                  }

                  if (serviceNo == 0)
                  {
                    Driver newDriver = Driver.createDriver(driverID[driverNoA],
                        startDate, startTime, endTime, tHours);
                    driverRoster[serviceNo] = newDriver;
                    service[serviceNo] = 1;
                    lastEndTime = endTime;
                    totalHours += tHours;
                    
                  }
                  else if (totalHours < 250 && (startTime - lastEndTime) > 20)
                  {
                    Driver newDriver = Driver.createDriver(driverID[driverNoA],
                        startDate, startTime, endTime, tHours);
                    driverRoster[serviceNo] = newDriver;
                    service[serviceNo] = 1;
                    lastEndTime = endTime;
                    totalHours += tHours;
                   
                  }
                  
                }
              }
            }

            out.printf("%-33s", startDate);
            out.println("\n");
            out.printf("%-25s", "Driver Name");
            out.printf("%13s", "Driver ID");
            out.printf("%13s", "Start time");
            out.printf("%13s", "End time");
            out.printf("%13s", "Service No");
            out.println("\n");

            for (serviceNo = 0; serviceNo < 61; serviceNo++)
            {

              // System.out.print(driverID[i]);
              // System.out.print(newDriver.getName() + " ");
              try
              {
                //out.println("             ");
                // TimeTable.setText("%-31s", newDriver.getName()));
                out.printf("%-23s", driverRoster[serviceNo].getName());
                out.printf("%13s", driverRoster[serviceNo].toStringID());
                out.printf("%13s", driverRoster[serviceNo].toStringStartTime());
                out.printf("%13s", driverRoster[serviceNo].toStringEndTime());
                out.printf("%13s", (6177 + serviceNo));

              }
              catch (Exception e)
              {// Catch exception if any
                System.err.println("Error2: " + e.getMessage());
              }
              out.println("\n");
            }
            out.println("\n");
            startDate.setDate(startDate.getDate() + 1);
          }
          out.close();

          try
          {
            reader = new FileReader("timetable.txt");
            TimeTable.read(reader, "timetable.txt");
          }
          catch (IOException exception)
          {
            System.err.println("Load oops");
            exception.printStackTrace();
          }
          finally
          {
            if (reader != null)
            {
              try
              {
                reader.close();
              }
              catch (IOException exception)
              {
                System.err.println("Error closing reader");
                exception.printStackTrace();
              }
            }
          }
        }

        else
        {

          Object[] options = { "OK" };
          JOptionPane.showOptionDialog(null,
              "The date that you provided must be Monday", "Warning",
              JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
              options, options[0]);

        }
      }
      else
      {
        Object[] options = { "OK" };
        JOptionPane.showOptionDialog(null,
            "The date that you provided is invalid", "Warning",
            JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
            options, options[0]);
      }
      /*
       * for (int x=0; x<5; x++) { startDate.setDate(startDate.getDate()+1);
       * System.out.println("                " + "Date:   " + startDate);
       * System.out.println(""); System.out.println("");
       * System.out.println("  Driver      " + "ServiceNo.        " +
       * "       Timetable" + ""); for (serviceNo = 0; serviceNo < 61;
       * serviceNo++) { //int[] serviceTimes = TimetableInfo.getServiceTimes(65,
       * // TimetableInfo.timetableKind.weekday, serviceNo); int[] serviceTimesd
       * = TimetableInfo.getServiceTimes(65, startDate, serviceNo);
       * 
       * System.out.print("              " + "  " + (6177 + serviceNo) +
       * "          ");
       * 
       * for (int i = 0; i < serviceTimesd.length; i++) {
       * 
       * System.out.print(serviceTimesd[i] + " ");
       * 
       * 
       * } System.out.println(""); } System.out.println("");
       * System.out.println("");
       * 
       * }
       */

    }

  }

  public boolean isValidDate(String date)
  {
    // set date format dd/MM/yyyy
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    // testDate variable
    Date testDate = null;

    // to parse the string into date form
    try
    {

      testDate = sdf.parse(date);

    }

    // if the format of the string provided doesn't match the format we
    // declared in SimpleDateFormat() we will get an exception

    catch (ParseException e)
    {

      return false;
    }

    // dateformat.parse will accept any date as long as it's in the format
    // you defined, it simply rolls dates over, for example, december 32
    // becomes jan 1 and december 0 becomes november 30
    // This statement will make sure that once the string
    // has been checked for proper formatting that the date is still the
    // date that was entered, if it's not, we assume that the date is invalid

    if (!sdf.format(testDate).equals(date))
    {
      return false;
    }
    else
      return true;

  } // end isValidDate

  public static void getPersonalTimeTable(int driverID, Date date)
  {
    int[] pserviceTimesd;
    int[] pdriverID;
    int pservice[] = new int[80];
    int pstartTime = 0;
    int pendTime = 0;
    int ptHours = 0;
    int pServiceNo;
    int plastEndTime = 0;
    int plastServiceNo;
    Date pstartDate = date;
    Driver pdriverRoster[] = new Driver[80];
    //FileWriter pstream;
    //PrintWriter pout = null;

    try
    {
      // Create file
      pstream = new FileWriter("PersonalTimetable.txt");
      pout = new PrintWriter(pstream);

      // Close the output stream

    }
    catch (Exception e)
    {// Catch exception if any
      System.err.println("Error4: " + e.getMessage());
    }
    if (pstartDate.getDay() == 1)
    {
      
      for (int x = 0; x < 5; x++)
      {
        int newday = 1;
        for (int pdriverNoA = 0; pdriverNoA < 50; pdriverNoA++)
        {
          plastEndTime = 0;
          int ptotalHours = 0;
          for (pServiceNo = 0; pServiceNo < 61; pServiceNo++)
          {
            if (pservice[pServiceNo] != 1)
            {
              pserviceTimesd = TimetableInfo.getServiceTimes(65, pstartDate,
                  pServiceNo);
              pdriverID = DriverInfo.getDrivers();

              for (int i = 0; i < pserviceTimesd.length; i++)
              {
                // System.out.print(serviceTimesd[i] + " ");
                if (i == 0)
                {
                  pstartTime = pserviceTimesd[i];
                  //System.out.println(pstartTime);
                }// if
                if (i == (pserviceTimesd.length - 1))
                {
                  pendTime = pserviceTimesd[i];
                  //System.out.println(pendTime);
                }// if
              }// for
              //System.out.println("test3");
              if ((pstartTime - plastEndTime) >= 20)
              {
                ptHours = pendTime - pstartTime;
              }

              if (pServiceNo == 0)
              {
                Driver newDriver = Driver.createDriver(pdriverID[pdriverNoA],
                    pstartDate, pstartTime, pendTime, ptHours);
                pdriverRoster[pServiceNo] = newDriver;
                pservice[pServiceNo] = 1;
                plastEndTime = pendTime;
                ptotalHours += ptHours;
                
              }
              else if (ptotalHours < 250 && (pstartTime - plastEndTime) > 20)
              {
                Driver newDriver = Driver.createDriver(pdriverID[pdriverNoA],
                    pstartDate, pstartTime, pendTime, ptHours);
                pdriverRoster[pServiceNo] = newDriver;
                pservice[pServiceNo] = 1;
                plastEndTime = pendTime;
                ptotalHours += ptHours;
             
              }
             
            }
          }//System.out.print(pdriverRoster[pServiceNo].getDriverId() + "  ");
        }
        for (pServiceNo = 0; pServiceNo < 61; pServiceNo++)
        {
          pserviceTimesd = TimetableInfo.getServiceTimes(65, pstartDate,
              pServiceNo);
          if (pdriverRoster[pServiceNo].getDriverId() == driverID)
          {
            if (newday == 1)
            {
            pout.printf("%-23s", "Date: "
                + pdriverRoster[pServiceNo].toStringDate() + "\n");
            newday = 0;
            }
            pout.println("================================================");
            //pout.printf("%-23s", pdriverRoster[pServiceNo].getName());
            //pout.printf("%13s", pdriverRoster[pServiceNo].toStringID());
            //pout.printf("%13s", pdriverRoster[pServiceNo].toStringStartTime());
            //pout.printf("%13s", pdriverRoster[pServiceNo].toStringEndTime());
            //pout.printf("%13s", pdriverRoster[pServiceNo].toStringTotalHours());
            pout.printf("%13s", "Service No.:" + "\n");
            pout.print("    " + (6177 + pServiceNo) + "     ");
            for (int i = 0; i < pserviceTimesd.length; i++)
            {
             //System.out.print(serviceTimesd[i] + " ");
             pout.print("   " + pserviceTimesd[i]);

             }// for
            pout.printf("\n");
            pout
                .println("-------------------------------------------------------");
            pout.printf("Total Working Hours:" + "%.2f",
                pdriverRoster[pServiceNo].getTotalHours());
            //float f = 2.3567f;System.out.printf("%.2f", f);
            pout.printf("\n");
            pout.printf("\n");
          }
        }
        // for
        pstartDate.setDate(pstartDate.getDate() + 1);
      }// for
      pout.close();
    }
    else
    {
      Object[] options = { "OK" };
      JOptionPane.showOptionDialog(null,
          "The date that you provided must be Monday", "Warning",
          JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
          options, options[0]);

    }
  }

}
